<?php

namespace App\Traits;

trait ApiResponse
{
    /**
     * 成功返回信息
     */
    public function success($msg = '操作成功!', $code = 0, $data = array())
    {
        return $this->data($data, 0, $code, $msg);
    }

    /**
     * 错误返回信息
     */
    public function fail($msg = 'error', $code = -1, $data = array())
    {
        return $this->data($data, 0, $code, $msg);
    }

    /**
     * 返回数据
     */
    public function data($data = [], $count = '0', $code = 0, $msg = 'success')
    {
        return response()->json(['code' => $code, 'msg' => $msg, 'count' => $count, 'data' => $data]);
    }

    /**
     * 数组赋值给对象
     *
     * @param array $array  数组资源
     * @param object $model 接收对象
     * @return mixed
     */
    public function arrayToObject(Array $array = [], $model)
    {
        foreach ($array as $key => $val) {
            if (property_exists($model, $key)) { // 如果有存在与key同名的属性，对应赋值
                $model->{$key} = $val;
            }
        }
        return $model;
    }

}
